﻿using System;
using TrafficArchives.DataAccess;
using TrafficArchives.Logs;
using TrafficArchives.Models;

namespace TrafficArchives.Units
{
    public partial class AddUnit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initlize();
            }
        }

        private void Initlize()
        {
            if (Request.QueryString["action"] == "edit" 
                && !string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                LblTitle.InnerText = LblTitle2.InnerText = "修改单位";
                var id = Request.QueryString["id"];
                var db = new UnitDb();
                var data = db.GetData(id);
                if (data.Rows.Count > 0)
                {
                    TxtName.Text = data.Rows[0]["dwname"].ToString();
                    TxtCode.Text = data.Rows[0]["dwglcode"].ToString();
                    TxtMaster.Text = data.Rows[0]["dwfzrname"].ToString();
                }
            }
            else
            {
                LblTitle.InnerText = LblTitle2.InnerText = "添加单位";
            }
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            var db = new UnitDb();
            var isEdit = Request.QueryString["action"] == "edit" && !string.IsNullOrEmpty(Request.QueryString["id"]);
            var data = isEdit ? db.GetData(Request.QueryString["id"]) : db.GetNoneData();
            if (!isEdit)
            {
                var newRow = data.NewRow();
                newRow["dwgl_id"] = Guid.NewGuid().ToString();
                data.Rows.Add(newRow);
            }
            data.Rows[0]["dwglcode"] = TxtCode.Text;
            data.Rows[0]["dwname"] = TxtName.Text;
            data.Rows[0]["dwfzrname"] = TxtMaster.Text;

            if (isEdit)
            {
                db.Update(data);
                var log = new LogInfo(LogType.修改单位);
                LogWriter.Writer(log);
            }
            else
            {
                db.Add(data);
                var log = new LogInfo(LogType.添加单位);
                LogWriter.Writer(log);
            }
            Response.Redirect("UnitView.aspx");
        }
    }
}